package cn.xmy.demo01.servlet;
import cn.xmy.demo01.pojo.Address;
import cn.xmy.demo01.service.AddressService;
import cn.xmy.demo01.service.impl.AddressServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/updateAddressServlet")
public class UpdateAddressServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AddressService addressService = new AddressServiceImpl();
        // 获取请求参数
        String id = request.getParameter("id");
        String name = request.getParameter("username");
        String phone = request.getParameter("phone");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String county = request.getParameter("county");
        String street = request.getParameter("street");

        // 构造 Address 对象
        Address address = new Address(id, name, phone, province, city, county, street);

        int rows = 0;
        try {
            // 调用服务层更新地址方法
            rows = addressService.updateAddress(address);
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        // 根据更新结果进行页面跳转
        if (rows > 0) {
            response.sendRedirect("address.html");
        } else {
            request.getRequestDispatcher("updateAddress.html").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
